﻿using RQX.Common.Core.Extension;
using RQX.Common.Core.Hardware.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RQX.Common.Core.Hardware.BaseCollection
{
    /// <summary>
    /// TCP服务端采集抽象类
    /// </summary>
    public abstract class AbstractTcpServerCollection : AbstractBaseCollection<TcpSocketServer>
    {
        #region 协议默认参数
        public override ProType ProType => ProType.TCPServer;
        public abstract string IP { get; }
        public abstract int Port { get; }
        #endregion
        protected AbstractTcpServerCollection() { }
        protected AbstractTcpServerCollection(StructureModel<TcpSocketServer> structureModel) : base(structureModel)
        {
            _conn.HandleServerAccepted = (socket) => Connect(StepType.Init, null);
            _conn.HandleMsgReceived = (c, buffer) => RecvData(buffer);
        }

        public override void Start(bool isUseReStart = true)
        {
            _conn.Start();
            Thread.Sleep(1000);
            base.Start(isUseReStart);
        }

        public override void Dispose()
        {
            _conn.Close();
            base.Dispose();
        }

        protected override void Send(byte[] buffer)
        {
            var socket = _conn._socketList.FirstOrDefault().Value;
            WriteSendLogMethod(BufferTransferToString(buffer));
            socket.Send(buffer);
        }
    }
}
